package com.feature.learn.concurrent.Semaphore.philosopher;

import java.util.concurrent.Semaphore;

public class PhilosophersTest {

    static final Semaphore count = new Semaphore(4);
    static final Semaphore[] mutex = {new Semaphore(1), new Semaphore(1),
            new Semaphore(1), new Semaphore(1), new Semaphore(1)};

    static class Philosopher extends Thread {
        Philosopher(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            do {
                try {
                    count.acquire(); // 期中一位获取信号，准备就餐
                    Integer i = Integer.parseInt(super.getName()); //根据标识准备拿筷子
                    mutex[i].acquire(); // 左边的筷子获取信号量
                    mutex[(i + 1) % 5].acquire(); // 右边的筷子也获取信号量
                    System.out.println(Thread.currentThread().getName() + " 哲学家【" + i + "】号吃了通心粉！"); // 吃饭
                    mutex[i].release();// 左边筷子释放
                    mutex[(i + 1) % 5].release(); // 右边筷子释放
                    count.release(); // 吃完了也释放信号量
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    System.err.println(Thread.currentThread().getName() + "哲学家执行时产生异常！");
                }
            } while (true);
        }
    }

    public static void main(String[] args) {
        Philosopher p0 = new Philosopher("0");
        Philosopher p1 = new Philosopher("1");
        Philosopher p2 = new Philosopher("2");
        Philosopher p3 = new Philosopher("3");
        Philosopher p4 = new Philosopher("4");

        p0.start();
        p1.start();
        p2.start();
        p3.start();
        p4.start();

    }
}
